package com.oa.kq.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.entity.Tips;
import com.mdp.core.query.QueryTools;
import com.mdp.core.service.SequenceService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.kq.entity.GroupPosition;
import com.oa.kq.service.GroupPositionService;
import com.oa.utils.ExcelView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Controller
@RequestMapping(value = "/**/oa/kq/groupPosition")
@Api(tags = {"考勤与地点关联表-操作接口"})
public class GroupPositionController {

    static Logger logger = LoggerFactory.getLogger(GroupPositionController.class);

    @Autowired
    private GroupPositionService groupPositionService;

    @Autowired
    private SequenceService seqService;

    /**
     * 跳转到查询页面listGroupPosition.jsp
     */
    @RequestMapping(value="/listGroupPosition")
    public ModelAndView listGroupPosition(@ModelAttribute("groupPosition") GroupPosition groupPosition, BindingResult result, Model model){
        ModelAndView mv = new ModelAndView();
        mv.addObject("data",groupPosition);
        return mv;
    }


    /**
     * 跳转到新增页面addGroupPosition.jsp
     */
    @RequestMapping(value="/addGroupPosition")
    public ModelAndView addGroupPosition(){

        ModelAndView mv = new ModelAndView();
        GroupPosition groupPosition=new GroupPosition();
        mv.addObject("data",groupPosition);
        return mv;
    }

    /**
     * 跳转到修改页面editGroupPosition.jsp
     */
    @RequestMapping(value="/editGroupPosition")
    public ModelAndView editGroupPosition( @ModelAttribute("groupPosition") GroupPosition groupPosition, BindingResult result, Model model){
        ModelAndView mv = new ModelAndView();
        groupPosition = groupPositionService.selectOneObject(groupPosition);	//根据ID读取
        mv.addObject("data",groupPosition);
        return mv;
    }


    /**
     * 请求需带json后缀,如selectListGroupPositionByPage.json
     * 根据条件查询数据对象列表
     */
    @RequestMapping(value="/selectListGroupPositionByPage")
    public ModelAndView selectListGroupPositionByPage( @ModelAttribute("groupPosition") GroupPosition groupPosition, BindingResult result, Model model){
        ModelAndView mv = new ModelAndView();

        List<GroupPosition>	groupPositionList = groupPositionService.selectListByWhere(groupPosition);	//列出GroupPosition列表
        mv.addObject("data",groupPositionList);
        Tips tips=new Tips("查询成功");
        mv.addObject("tips", tips);
        return mv;
    }

    /**
     * 新增一条数据
     */
    @RequestMapping(value="/insertGroupPosition")
    public ModelAndView insertGroupPosition( @ModelAttribute("groupPosition") GroupPosition groupPosition, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips=new Tips("成功新增一条数据");
        if(StringUtils.isEmpty(groupPosition.getId())){
            groupPosition.setId(seqService.getTablePK("groupPosition", "id"));
        }
        groupPositionService.insert(groupPosition);
        mv.addObject("data",groupPosition);
        mv.addObject("tips", tips);
        return mv;
    }

    /**
     * 根据主键删除1条数据
     */
    @RequestMapping(value="/deleteGroupPositionByPk")
    public ModelAndView deleteGroupPositionByPk(@ModelAttribute("groupPosition") GroupPosition groupPosition, BindingResult result){
        ModelAndView mv = new ModelAndView();
        Tips tips=new Tips("成功删除一条数据");
        groupPositionService.deleteByPk(groupPosition);
        mv.addObject("tips", tips);
        return mv;
    }

    /**
     * 根据主键修改一条数据
     */
    @RequestMapping(value="/updateGroupPositionByPk")
    public ModelAndView updateGroupPositionByPk( @ModelAttribute("groupPosition") GroupPosition groupPosition, BindingResult result, Model model) {
        ModelAndView mv = new ModelAndView();
        Tips tips=new Tips("成功更新一条数据");
        groupPositionService.updateByPk(groupPosition);
        mv.addObject("data",groupPosition);
        mv.addObject("tips", tips);
        return mv;
    }




    /**
     * 批量删除
     */
    @RequestMapping(value="/batchDeleteGroupPosition")
    public ModelAndView batchDeleteGroupPosition(@RequestParam("id[]") String[] id) {
        ModelAndView mv = new ModelAndView();
        Tips tips=new Tips("成功删除"+id.length+"条数据");
        List<GroupPosition> list=new ArrayList<GroupPosition>();
        for(int i=0;i<id.length;i++){
            GroupPosition groupPosition=new GroupPosition();
            groupPosition.setId(id[i]);
            list.add(groupPosition);
        }
        groupPositionService.batchDelete(list);
        mv.addObject("tips", tips);
        return mv;
    }

    /*
     * 导出到excel
     * @return
     */
    @RequestMapping(value="/exportGroupPositionToExcel")
    public ModelAndView exportGroupPositionToExcel( @ModelAttribute("groupPosition") GroupPosition groupPosition, BindingResult result, Model model){
        ModelAndView mv = new ModelAndView();
        Tips tips=new Tips("成功导出数据");
        try{
            Map<String,Object> dataMap = new HashMap<String,Object>();
            List<String> titles = new ArrayList<String>();
            titles.add("编号");
            titles.add("经度");
            titles.add("纬度");
            titles.add("位置描述");
            titles.add("位置名称");
            titles.add("所属组别id");
            dataMap.put("titles", titles);
            List<GroupPosition> GroupPositionList = groupPositionService.selectListByWhere(groupPosition);
            List<Map<String,Object>> allList = new ArrayList<Map<String,Object>>();
            for(int i=0;i<GroupPositionList.size();i++){
                Map<String,Object> row = new HashMap<String,Object>();
                row.put("var1", GroupPositionList.get(i).getId());
                row.put("var2", GroupPositionList.get(i).getLongitude());
                row.put("var3", GroupPositionList.get(i).getLatitude());
                row.put("var4", GroupPositionList.get(i).getPosition());
                row.put("var5", GroupPositionList.get(i).getPositionName());
                row.put("var6", GroupPositionList.get(i).getGroupId());
                allList.add(row);
            }
            dataMap.put("varList", allList);
            ExcelView erv = new ExcelView();
            mv = new ModelAndView(erv,dataMap);
        } catch(Exception e){
            logger.error(e.toString(), e);
            tips.setErrMsg("导出数据异常");
        }
        mv.addObject("tips", tips);
        return mv;
    }

    @ResponseBody
    @ApiOperation(value = "考勤与地点关联表-查询列表", notes = " ")
    @ApiEntityParams(GroupPosition.class)
    @ApiResponses({@ApiResponse(code = 200, response = GroupPosition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listGroupPosition(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        QueryWrapper<GroupPosition> qw = QueryTools.initQueryWrapper(GroupPosition.class, params);
        IPage page = QueryTools.initPage(params);
        List<Map<String, Object>> datas = groupPositionService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @ResponseBody
    @ApiOperation(value = "考勤与地点关联表-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = GroupPosition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addGroupPosition(@RequestBody GroupPosition groupPosition) {
        groupPositionService.save(groupPosition);
        return Result.ok("add-ok", "添加成功！");
    }
    @ResponseBody
    @ApiOperation(value = "考勤与地点关联表-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delGroupPosition(@RequestBody GroupPosition groupPosition) {
        groupPositionService.removeById(groupPosition);
        return Result.ok("del-ok", "删除成功！");
    }
    @ResponseBody
    @ApiOperation(value = "考勤与地点关联表-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = GroupPosition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editGroupPosition(@RequestBody GroupPosition groupPosition) {
        groupPositionService.updateById(groupPosition);
        return Result.ok("edit-ok", "修改成功！");
    }
    @ResponseBody
    @ApiOperation(value = "考勤与地点关联表-批量修改某些字段", notes = "")
    @ApiEntityParams(value = GroupPosition.class, props = {}, remark = "考勤与地点关联表", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = GroupPosition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        groupPositionService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }
    @ResponseBody
    @ApiOperation(value = "考勤与地点关联表-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelGroupPosition(@RequestBody List<GroupPosition> groupPositions) {
        User user = LoginUtils.getCurrentUserInfo();
        if (groupPositions.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<GroupPosition> datasDb = groupPositionService.listByIds(groupPositions.stream().map(i -> i.getId()).collect(Collectors.toList()));

        List<GroupPosition> can = new ArrayList<>();
        List<GroupPosition> no = new ArrayList<>();
        for (GroupPosition data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            groupPositionService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }

        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }
    @ResponseBody
    @ApiOperation(value = "考勤与地点关联表-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = GroupPosition.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(GroupPosition groupPosition) {
        GroupPosition data = (GroupPosition) groupPositionService.getById(groupPosition);
        return Result.ok().setData(data);
    }

}
